<template>
	<view class="dk-container">
		<view class="dk-item" @click="openStoreSelectToast()"><image src="../../static/toStore/storeCheck-icon.png"></image>助店打卡</view>
		<view class="dk-item" @click="goStoreRecordPage()"><image src="../../static/toStore/storeRecord-icon.png"></image>助店记录</view>
		<view class="dk-item" @click="goStoreTodoPage()"><image src="../../static/toStore/toStoreTodo-icon.png"></image>助店待办</view>
		<!-- <view class="dk-item" @click="goStoreBranchPage()"><image src="../../static/toStore/toStoreBranch-icon.png"></image>网点招商</view> -->
		<view class="dk-item" @click="showTab"><image src="../../static/toStore/toStoreBranch-icon.png"></image>网点招商</view>
		
		
		<!-- 助店打卡选择助店的店面 -->
		<view class="store-select-shdow" v-if="storeSelectToast"></view>
		<view class="store-select-toast" v-if="storeSelectToast">
			<view class="toast-clone" @click="storeSelectToast = false"></view>
			<view class="store-search">
				<input v-model="searchValue" type="text" :border="false" @input="storeListSearch" placeholder="请选择" />
			</view>
			<view class="store-list">
				<scroll-view class="scroll-Y" :scroll-top="scrollTop" scroll-y="true">
					<!-- {{province}}--{{city}}--{{latitude}}--{{longitude}} -->
					<view class="store-list-item" v-for="item in allStoreList" :key="item.storeName" @click="confirmStore(item)">{{item.storeName}}</view>
				</scroll-view>
			</view>
		</view>
		<u-toast ref="uToast" />
		<view class="tab-popup-wrap" v-if="tabShow">
			<view class="tab-box">
				<view class="tab-img">
					<view class="img-item" @click="goStoreBranchPage()">
						<image src="../../static/logs/tab1.png" mode=""></image>
						<view class="img-text">
							网点招商
						</view>
					</view>
					<view class="img-item" @click="tabJump('/pages/quotientList/quotientList')">
						<image src="../../static/logs/tab2.png" mode=""></image>
						<view class="img-text">
							选商备案
						</view>
					</view>
					<view class="img-item" @click="tabJump('/pages/logFollowList/logFollowList')">
						<image src="../../static/logs/tab3.png" mode=""></image>
						<view class="img-text">
							日志跟进
						</view>
					</view>
					
					
				</view>
				<image src="../../static/logs/close.png" mode="" class="close-icon" @click="tabShow=false"></image>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getNearByStores,
		getStoreList,
		wxGetTxMapByLatLng
	} from '../../common/service.js'
	import utils from '../../common/utils.js'
	export default {
		data() {
			return {
				province: '',
				city: '',
				// latitude:'39.834312438964844',
				// longitude:'116.39422607421875',
				latitude:'',
				longitude:'',
				searchValue: '',
				tempValue:'',
				storeSelectToast: false,
				allStoreList:[],
				scrollTop: 0,
				flag: 1,
				tabShow:false
			};
		},
		onLoad: function(option) {
			const that = this
			this.LOGINACTION();
			// 获取用户当前定位
			that.INITWXJSDK(that.CONFIG.appid, location.origin + location.pathname + location.search, function() {
				that.$wx.getLocation({
					type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
					success: function(res) {
						console.log('获取到当前地理位置信息(只有经纬度,省市要另外获取)：');
						console.log(res);
						that.latitude = res.latitude;
						that.longitude = res.longitude;
						// console.log('latitude:' + that.latitude);
						// console.log('longitude:' + that.longitude);
						
						// 根据经纬度查询省市区
						// const latLng = new qq.maps.LatLng(that.latitude, that.longitude);
						// that.geocoder.getAddress(latLng);
						that.getLocInfo()
					},
					cancel: function(res) {
						alert('用户拒绝授权获取地理位置');
					}
				});
			}, ['getLocation'])
			
			
			// 经纬度转地址
			// that.geocoder = new qq.maps.Geocoder({
			// 	complete: function(result) {
			// 		console.log('根据经纬度，获取到地址信息:');
			// 		console.log(result);
			// 		const province = result.detail.addressComponents.province;
			// 		const city = result.detail.addressComponents.city;
			// 		that.province = province
			// 		that.city = city
					
			// 		// 根据经纬度 省/市
			// 		that.getNearLocation()
			// 	}
			// });
			
			
			// 本地模拟定位成功
			// const latLng = new qq.maps.LatLng(that.latitude, that.longitude);
			// that.geocoder.getAddress(latLng);
			
			// 阻止页面滑动
			that.stop()
		},
		onShow: function() {
			const that = this;	
		},
		methods: {
			showTab(){
				this.tabShow=true
			},
			// 经纬度转地址
			getLocInfo(){
				let that = this
				wxGetTxMapByLatLng({"lat":that.latitude,"lng":that.longitude}, (res)=>{
					if(res.data.status=='00000'){
						let result = res.data.data.result
						const province = result.address_component.province;
						const city = result.address_component.city;
						that.province = province
						that.city = city
						// 根据经纬度 省/市
						that.getNearLocation()
					}else{
						uni.showToast({
							message: res.data.message,
							duration: 2000,
							icon: 'error'
						})
					}
				})
			},
			// 阻止页面滚动
			stop(){
				var box=function(e){passive: false ;};
				document.body.style.overflow='hidden';
				document.addEventListener("touchmove",box,false);
			},
			// 允许页面滚动
			move(){
				var box=function(e){passive: false };
				document.body.style.overflow=''; // 出现滚动条
				document.removeEventListener("touchmove",box,false);
			},
			// 打卡详情
			emitDataFunc: function(item) {
				// 门店定位地址
				if(item.latitude && item.longitude){
					// 定位地址和门店地址距离计算
					const distance = this.getGreatCircleDistance(this.latitude*1, this.longitude*1, item.latitude*1, item.longitude*1)
					let isTest = location.href.indexOf('webtest') > -1;					
					if(distance > 0.5 && !isTest){
						this.$refs.uToast.show({
							title: '该店面地址不在打卡范围内，请确认打卡位置或手机定位是否开启'+'当前：'+this.latitude +','+ this.longitude +'店面：' + item.latitude + ',' +item.longitude,
							type: 'error',
							duration: 3000,
							callback: function() {
								return;
							}
						});
					} else {
						console.log('item',item)
						// return
						// 助店打卡详情
						uni.navigateTo({
							url: `../toStoreDetail/index?id=${item.id}`
						});
					}
					
				} else {
					this.$refs.uToast.show({
						title: '该店面地址为空，先到图像采集维护店面地址再进行助店打卡',
						type: 'error',
						duration: 3000,
						callback: function() {
							return;
						}
					});
				}
			},
			
			// 店铺选择输入查询/模糊查询
			storeListSearch(e){
				const that = this
				that.flag = 1
				that.searchValue = e.detail.value
			
				// 请求查询接口
				if(that.searchValue.length > 0 && that.searchValue!=that.tempValue){
					// alert('查询门店列表')
					that.queryAjaxJson()
				}
			
				// 输入关键字临时存放一下，解决uniapp input执行两次的问题
				that.tempValue = that.searchValue
				
				// 输入框清空时，重新查询定位附件的门店
				if(that.searchValue.length == 0){
					that.flag = 2
					if(that.latitude && that.longitude && that.province && that.city){
						// alert('有经纬度省/市，开始请求附件门店')
						that.getNearLocation()
					} else {
						that.allStoreList = [];
					}
				}
			},
			// 模糊查询门店接口
			queryAjaxJson(){
				console.log('queryAjaxJson',this.searchValue)
				const that = this
				const params = {
					code: this.getCode() || '',
					storeName: this.searchValue || ''
				}
				
				getStoreList(params, function(resuser) {
					if (resuser && resuser.statusCode == 200) {
						console.log(that.flag)
						if(that.flag != 1) return
						const res = resuser.data;
						that.allStoreList = res.data
					}
				}, function(e) {
				});
			},
			
			// 两个地址（经纬度）计算距离
			getGreatCircleDistance(lat1, lon1, lat2, lon2) {
			  const radians = Math.PI / 180;
			  const R = 6371; // 地球半径，单位为公里
			 
			  const deltaLat = (lat2 - lat1) * radians;
			  const deltaLon = (lon2 - lon1) * radians;
			 
			  lat1 = lat1 * radians;
			  lat2 = lat2 * radians;
			 
			  const sinThreshold = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
								   Math.cos(lat1) * Math.cos(lat2) *
								   Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
			  const angle = 2 * Math.atan2(Math.sqrt(sinThreshold), Math.sqrt(1 - sinThreshold));
			  return angle * R;
			},
			
			// 根据定位查询附件的门店
			getNearLocation() {
				const that = this;
				const params = {
					province: that.province||'',
					city: that.city||'',
					latitude: that.latitude||'',
					longitude: that.longitude||''
				};
				getNearByStores(params, function(res) {
					if (res.statusCode == 200) {
						const rs = res.data;
						if (rs && rs.code == 200) {
							const pointsListRes = rs.data || [];
							
							that.allStoreList = [];
							if (pointsListRes) {
								for (const item in pointsListRes) {
									const obj = pointsListRes[item];
									obj.RANGE = item;
									that.allStoreList.push(obj);
								}
							}
							// alert('附件门店返回数据--第一条')
							// alert(that.allStoreList[0].storeName)
							console.log('可选的附近门店:');
							console.log(that.allStoreList);
						} else {
							that.$refs.uToast.show({
								title: rs.msg || '没有查询到定位附近的门店，请手动选择',
								type: 'error',
								duration: 3000,
								callback: function() {
									return;
								}
							});
						}
					}
				}, function(e) {
				});
			},
			
			// 获取用户ID
			getCode: function() {
				return this.CONFIG.user.id;
			},
			
			// 打开门店列表选择门店
			openStoreSelectToast(){
				// this.storeSelectToast = true
        uni.navigateTo({
					url: '../toStoreList/index'
				});
			},
			
			// 助店记录
			goStoreRecordPage(){
				uni.navigateTo({
					url: '../storeRcordList/index'
				});
			},
			// 助店待办管理
			goStoreTodoPage(){
				uni.navigateTo({
					url: '../toStoreTodo/list'
				});
			},
			goStoreBranchPage() {
				uni.navigateTo({
					url: '../toStoreBranchInvest/list'
				});
			},
			tabJump(url){
				uni.navigateTo({
					url
				})
			}
		}
	};
</script>

<style lang="scss">
	page{
		width: 100%;
		height: 100%;
		padding: 0;
		margin: 0;
	}
	.dk-container {
		width: 100%;
		height: 100%;
		padding: 0;
		margin: 0;
		position: relative;
		padding-top: 355rpx;
		background: url('../../static/toStore/store-check-banner-2.png') no-repeat left -13rpx #F3F5F7;
		background-size: 750rpx 493rpx;
		box-sizing: border-box;
	}
	.dk-item{
		width: 690rpx;
		height: 162rpx;
		display: flex;
		align-items: center;
		line-height: 162rpx;
		background: #FFFFFF;
		box-shadow: 0px 6rpx 12rpx 0px rgba(221,221,221,0.5);
		border-radius: 16rpx;
		margin: 0 auto 20rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 30rpx;
		color: #333333;
	}
	.dk-item image{
		width: 104rpx;
		height: 104rpx;
		margin-left: 23rpx;
		margin-right: 13rpx;
	}
	/* 助店打卡选择助店的店面 */
	.store-select-shdow{
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 88;
		background: rgba(0,0,0,0.3);
	}
	.store-select-toast{
		position: fixed;
		left: 50%;
		top: 200rpx;
		z-index: 99;
		margin-left: -345rpx;
		width: 690rpx;
		height: calc(100% - 400rpx);
		background: #FFFFFF;
		border-radius: 30rpx;
	}
	.toast-clone{
		position: absolute;
		top: -16rpx;
		right: -16rpx;
		width: 42rpx;
		height: 42rpx;
		background: url('../../static/toStore/clone.png') no-repeat center;
		background-size: 42rpx;
	}
	.store-search{
		display: flex;
		width: 620rpx;
		height: 98rpx;
		padding-left: 72rpx;
		background: url('../../static/toStore/search.png') no-repeat 30rpx 33rpx #F7F7F7;
		background-size: 32rpx;
		border-radius: 16rpx;
		margin: 53rpx auto 20rpx;
		align-items: center;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #333333;
		input{
			display: block;
			width: 100%;
			height: 100%;
		}
	}
	.scroll-Y{
		height: 100%;
	}
	.store-list{
		border-radius: 0 0 30rpx 30rpx;
		height: calc(100% - 171rpx);
		overflow: hidden;
	}
	.store-list-item{
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #555555;
		line-height: 48rpx;
		padding: 20rpx 35rpx;
		border-bottom: 1px solid #F2F2F2;
	}
	// toast提示框样式修改
	/deep/.u-toast{
		padding: 26rpx 30rpx;
	}
	/deep/.u-type-error{
		background: #E2F0FF;
		border-radius: 10rpx;
		border: 1rpx solid #007AFF;
	}
	/deep/.u-type-error .u-icon-wrap{
		width: 40rpx;
		height: 40rpx;
		background: url('../../static/toStore/tips2.png') no-repeat;
		background-size: contain;
	}
	/deep/.u-icon{
		display: none;
	}
	/deep/.u-type-error .u-text{
		max-width: calc(100% - 40rpx);
		padding-left: 14rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #007AFF;
	}
	.tab-popup-wrap{
		width: 100vw;
		height: 100vh;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 10;
		background:rgba(255,255,255,0.4);
		-webkit-backdrop-filter: blur(10px);
		backdrop-filter: blur(10px);
		.tab-box{
				position: absolute;
				width: 100%;
				height: 200rpx;
				bottom: 300rpx;
				left: 0;
				.tab-img{
					display: flex;
					justify-content: space-evenly;
					image{
						width: 134rpx;
						height: 134rpx;
					}
					.img-text{
						color: #999;
						font-size: 30rpx;
						text-align: center;
					}
					
				}
				.close-icon{
					width: 50rpx;
					height: 50rpx;
					display: block;
					margin: 0 auto;
					margin-top: 140rpx;
				}
		}
	}
</style>
